package com.luxiu;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * 共享内存
 */
public class ShareMemory {
    public static void demo() throws IOException {
        Pipe pipe = Pipe.open();
        Pipe.SinkChannel sinkChannel = pipe.sink(); // sink 通道写入数据
        String data = "some string";

        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.clear();
        buffer.put(data.getBytes());

        buffer.flip(); // 反转缓冲区，准备被读取
        while (buffer.hasRemaining()) {
            sinkChannel.write(buffer); // 将 Buffer 的数据写入 sink 通道
        }

        Pipe.SourceChannel sourceChannel = pipe.source(); // 源通道读取数据
        ByteBuffer readBuffer = ByteBuffer.allocate(32);
        int bytesRead = sourceChannel.read(readBuffer); // 返回值代表读取了多少数据
        System.out.println("Read: " + bytesRead); // Read: 11
        System.out.println(new String(readBuffer.array())); // some string

        System.out.println("over");
    }

    public static void main(String[] args) {
        try {
            demo();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
